package cn.com.libertymutual.sp.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.BeanUtilExt;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.PosterAnimatedText;
import cn.com.libertymutual.sp.bean.SysOperationLog;
import cn.com.libertymutual.sp.bean.TbSpApprove;
import cn.com.libertymutual.sp.bean.TbSpArticle;
import cn.com.libertymutual.sp.bean.TbSpFlow;
import cn.com.libertymutual.sp.bean.TbSpFlowDetail;
import cn.com.libertymutual.sp.bean.TbSpPoster;
import cn.com.libertymutual.sp.bean.TbSpProduct;
import cn.com.libertymutual.sp.bean.TbSpProductConfig;
import cn.com.libertymutual.sp.bean.TbSysHotarea;
import cn.com.libertymutual.sp.dao.ApproveDao;
import cn.com.libertymutual.sp.dao.ArticleDao;
import cn.com.libertymutual.sp.dao.FlowDao;
import cn.com.libertymutual.sp.dao.FlowDetailDao;
import cn.com.libertymutual.sp.dao.OperationLogDao;
import cn.com.libertymutual.sp.dao.PosterAnimatedTextDao;
import cn.com.libertymutual.sp.dao.PosterDao;
import cn.com.libertymutual.sp.dao.ProductConfigDao;
import cn.com.libertymutual.sp.dao.ProductDao;
import cn.com.libertymutual.sp.dao.StoreProductDao;
import cn.com.libertymutual.sp.dao.TbSysHotareaDao;
import cn.com.libertymutual.sp.dto.RateDto;
import cn.com.libertymutual.sp.service.api.InsureService;
import cn.com.libertymutual.sp.service.api.PosterService;
import cn.com.libertymutual.sp.service.api.ShopService;
import cn.com.libertymutual.sys.dao.ISysRoleUserDao;

@Service("posterService")
public class PosterServiceImpl implements PosterService {
	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private ProductDao productDao;
	@Autowired
	private PosterAnimatedTextDao animatedTextDao;
	@Autowired
	private FlowDetailDao flowDetailDao;
	@Autowired
	private PosterDao posterDao;
	@Autowired
	private ApproveDao approveDao;
	@Autowired
	private ArticleDao articleDao;
	@Autowired
	private ProductConfigDao productConfigDao;
	@Autowired
	private OperationLogDao operationLogDao;
	@Autowired
	private InsureService insureService;
	@Autowired
	private StoreProductDao storeProductDao;
	@Resource
	private RedisUtils redisUtils;
	@Autowired
	private JdbcTemplate readJdbcTemplate;
	@Autowired
	private TbSysHotareaDao hotareaDao;
	@Autowired
	private ShopService shopService;
	@Autowired
	private ISysRoleUserDao roleUserDao;
	@Autowired
	private FlowDao flowDao;

	@Override
	public ServiceResult posterList(String productName, String riskCode, String name, String type, String status, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "status"));
		orders.add(new Order(Direction.ASC, "id"));
		Sort sort = new Sort(orders);
		String userId = Current.userId.get();
		Integer roleId = roleUserDao.findByUserid(userId).getRoleid();
		Page<TbSpPoster> page = posterDao.findAll(new Specification<TbSpPoster>() {
			public Predicate toPredicate(Root<TbSpPoster> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(productName)) {
					log.info(productName);
					predicate.add(cb.like(root.get("productName").as(String.class), "%" + productName + "%"));
				}
				if (StringUtils.isNotEmpty(riskCode) && !"-1".equals(riskCode)) {
					log.info(riskCode);
					predicate.add(cb.equal(root.get("riskCode").as(String.class), riskCode));
				}

				if (StringUtils.isNotEmpty(name)) {
					log.info(name);
					predicate.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
				}
				if (StringUtils.isNotEmpty(type) && !"-1".equals(type)) {
					log.info(type);
					predicate.add(cb.like(root.get("type").as(String.class), "%" + type + "%"));
				}
				if (StringUtils.isNotEmpty(status) && !"-1".equals(status)) {
					log.info(status);
					predicate.add(cb.equal(root.get("status").as(String.class), status));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));

		if (CollectionUtils.isNotEmpty(page.getContent())) {
			List<TbSpPoster> list = page.getContent();
			for (TbSpPoster tsp : list) {
				// TbSpApprove tsa = approveDao.findByTypeAndApproveId(Constants.POSTER_APPROVE,
				// tsp.getId().toString(), Constants.APPROVE_WAIT);
				TbSpApprove tsa = approveDao.findApproveFlow(Constants.POSTER_APPROVE, tsp.getId().toString(), Constants.APPROVE_WAIT,
						Constants.FLOW_POSTER);
				if (null != tsa) {
					tsp.setTbSpApprove(tsa);
					TbSpFlowDetail flowDetail = flowDetailDao.findByNoAndNode(tsa.getFlowNo(), tsa.getFlowNode());
					if (null != flowDetail && StringUtils.isNotBlank(flowDetail.getUserCode())) {// 用户审批
						String[] users = flowDetail.getUserCode().split("&");
						boolean b = Arrays.asList(users).contains(userId);
						if (b) {
							tsp.setApproveAuth("true");
						} else {
							tsp.setApproveAuth("false");
						}
					}
					if (null != flowDetail && StringUtils.isNotBlank(flowDetail.getRoleCode())) {// 角色审批
						String[] roles = flowDetail.getRoleCode().split("&");
						boolean b = Arrays.asList(roles).contains(roleId.toString());
						if (b) {
							tsp.setApproveAuth("true");
						} else {
							tsp.setApproveAuth("false");
						}
					}
				}
				List<PosterAnimatedText> animatedList = animatedTextDao.findByPosterId(tsp.getId());
				if (CollectionUtils.isNotEmpty(animatedList)) {
					tsp.setAnimatedTexts(animatedList);
				}
			}
		}
		sr.setResult(page);
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult addOrUpdatePoster(TbSpPoster tbSpPoster) {
		ServiceResult sr = new ServiceResult();
		TbSpFlow flow = flowDao.findByType(Constants.FLOW_POSTER);
		if (null == flow) {
			sr.setFail();
			sr.setResult("请先配置海报审批流！");
			return sr;
		}
		List<TbSpFlowDetail> details = flowDetailDao.findByFlowNo(flow.getFlowNo());
		if (CollectionUtils.isNotEmpty(details) && details.size() <= 1) {
			sr.setFail();
			sr.setResult("请先配置海报审批流！");
			return sr;
		}
		String status = tbSpPoster.getStatus();
		if (null == tbSpPoster.getId()) {// 添加
			log.info("---------添加海报-----------");
			tbSpPoster.setCreateDate(new Date());
			tbSpPoster.setViews(0);
			tbSpPoster.setUserId(Current.userInfo.get().getUserId());
			tbSpPoster.setStatus(Constants.APPROVE_ADD);
			posterDao.save(tbSpPoster);
			tbSpPoster.setId(tbSpPoster.getId());
			TbSpPoster newtp = new TbSpPoster();
			try {
				BeanUtilExt.copyProperties(newtp, tbSpPoster);
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			newtp.setStatus(status);
			String jsonstring = JSONObject.toJSONString(newtp, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
			TbSpApprove tsa = new TbSpApprove();
			tsa.setStatus(Constants.FALSE);
			tsa.setApproveId(tbSpPoster.getId().toString());
			tsa.setContent(jsonstring);
			tsa.setOriginalStatus(status);
			tsa.setApplyTime(new Date());
			tsa.setFlowNo(flow.getFlowNo());
			tsa.setFlowType(Constants.FLOW_POSTER);
			tsa.setFlowNode(flow.getLastFlowNode());
			tsa.setApplyUser(Current.userInfo.get().getUserId());
			tsa.setType(Constants.POSTER_APPROVE);
			approveDao.save(tsa);
			sr.setResult(tbSpPoster);
		} else {// 修改
			log.info("---------修改海报-----------");

			tbSpPoster.setModifyUser(Current.userInfo.get().getUserId());
			Optional<TbSpPoster> optbSpPoster = posterDao.findById(tbSpPoster.getId());
			TbSpPoster dbtbSpPoster = optbSpPoster.get();
			// TbSpPoster dbtbSpPoster = posterDao.findOne(tbSpPoster.getId());1.5.10

			TbSpPoster newtbSpPoster = new TbSpPoster();
			try {
				BeanUtilExt.copyProperties(newtbSpPoster, dbtbSpPoster);
			} catch (InvocationTargetException e1) {
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			}

			boolean updateAnimated = false;
			List<PosterAnimatedText> animatedTexts = animatedTextDao.findByPosterId(tbSpPoster.getId());
			if (animatedTexts.size() != tbSpPoster.getAnimatedTexts().size() || !animatedTexts.containsAll(tbSpPoster.getAnimatedTexts())) {
				updateAnimated = true;
			}
			if (!newtbSpPoster.differ(tbSpPoster) || updateAnimated) {
				log.info("===============differ后不相同==================");
				try {
					TbSpPoster beantbSpPoster = (TbSpPoster) BeanUtilExt.differAbeanToBbean(newtbSpPoster, tbSpPoster);
					log.info("====beandiffer====:" + beantbSpPoster.toString());
					String jsonstring = JSONObject.toJSONString(beantbSpPoster, SerializerFeature.WriteMapNullValue,
							SerializerFeature.WriteNullStringAsEmpty);
					log.info(jsonstring);
					// 记录在审批表中
					TbSpApprove dbtsa = approveDao.findApproveFlow(Constants.POSTER_APPROVE, dbtbSpPoster.getId().toString(), Constants.APPROVE_WAIT,
							Constants.FLOW_POSTER);
					if (null != dbtsa) {
						dbtsa.setContent(jsonstring);
						approveDao.save(dbtsa);
					} else {
						TbSpApprove tsa = new TbSpApprove();
						tsa.setStatus(Constants.FALSE);
						tsa.setApproveId(dbtbSpPoster.getId().toString());
						tsa.setContent(jsonstring);
						tsa.setOriginalStatus(dbtbSpPoster.getStatus());
						tsa.setApplyTime(new Date());
						tsa.setFlowNo(flow.getFlowNo());
						tsa.setFlowType(Constants.FLOW_POSTER);
						tsa.setFlowNode(flow.getLastFlowNode());
						tsa.setApplyUser(Current.userInfo.get().getUserId());
						tsa.setType(Constants.POSTER_APPROVE);
						approveDao.save(tsa);
					}
					if (Constants.TRUE.equals(dbtbSpPoster.getStatus())) {
						dbtbSpPoster.setStatus(Constants.APPROVE_UP_UPDATE);
					} else {
						dbtbSpPoster.setStatus(Constants.APPROVE_DOWN_UPDATE);
					}
					posterDao.save(dbtbSpPoster);
					sr.setResult(jsonstring);
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			} else {
				log.info("===============differ后相同==================");
				TbSpPoster savetbSpPoster = posterDao.save(tbSpPoster);
				sr.setResult(savetbSpPoster);
			}
		}
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult approve(String approveType, Integer id, String type, String remark) {
		ServiceResult sr = new ServiceResult();
		String userId = Current.userInfo.get().getUserId();
		SysOperationLog operLog = new SysOperationLog();
		operLog.setIP(Current.IP.get());
		operLog.setLevel("1");

		operLog.setOperationTime(new Date());
		operLog.setUserId(userId);
		// 审批信息
		List<TbSpApprove> dbtsalist = approveDao.findConfigByTypeAndApproveId(approveType, id.toString(), Constants.APPROVE_WAIT);
		TbSpApprove dbtsa = null;
		if (CollectionUtils.isEmpty(dbtsalist)) {
			sr.setFail();
			sr.setResult("未找到要审批的记录！");
			return sr;
		}
		dbtsa = dbtsalist.get(0);
		dbtsa.setUserId(userId);
		dbtsa.setApproveTime(new Date());
		dbtsa.setRemark(remark);

		if ("yes".equals(type)) {

			dbtsa.setStatus(Constants.APPROVE_YES);

			if (Constants.PRODUCT_APPROVE.equals(approveType)) {// 审批产品
				// 记录日志
				operLog.setContent(userId + "审批ID为" + id + "的产品的添加或者修改--通过");
				operLog.setModule("产品管理");
				// 是否有下级审批
				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(), thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					JSONObject json = JSONObject.parseObject(dbtsa.getContent());
					TbSpProduct tsp = JSONObject.toJavaObject(json, TbSpProduct.class);
					log.info("-----json----tsp--:{}", tsp.getProductConfigs());
					List<TbSpProductConfig> productConfigs = tsp.getProductConfigs();
					for (TbSpProductConfig tp : productConfigs) {
						productConfigDao.updateInfo(tp.getStatus(), tp.getRate(), tp.getBranchCode(), tp.getProductId());
					}
					// boolean hasSave = false;
					// 如果原来是下架改为上架或者新上架产品，批量自动上架到店铺(只针对非专属产品)
					if (Constants.FALSE.equals(tsp.getIsExclusive())) {
						// if (null != tsp.getId()) {
						if (!Constants.TRUE.equals(dbtsa.getOriginalStatus()) && Constants.TRUE.equals(tsp.getStatus())) {// 再次上架
							storeProductDao.insertAutoMatic(tsp.getId());
						}
						// } else {
						// // 新上架，
						// if (Constants.TRUE.equals(tsp.getStatus())) {
						// TbSpProduct savetsp = productDao.save(tsp);
						// storeProductDao.insertAutoMatic(savetsp.getId());
						// hasSave = true;
						// }
						// }
					}
					// if (!hasSave) {
					productDao.save(tsp);
					// }
					if (Constants.FALSE.equals(tsp.getStatus())) {// 如果下架产品，则同步店铺的产品
						productConfigDao.updateStatus(Constants.FALSE, id);
						storeProductDao.deleteByProId(id);
					}
					redisUtils.deletelike(Constants.RISK_CODE_NAME_INFO);
					sr.setResult(tsp);
				}
			} else if (Constants.ARTICLE_APPROVE.equals(approveType)) {
				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(), thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					JSONObject json = JSONObject.parseObject(dbtsa.getContent());
					TbSpArticle tsa = JSONObject.toJavaObject(json, TbSpArticle.class);
					articleDao.save(tsa);
				}
				operLog.setContent("审批ID为" + id + "的文章的添加或者修改--通过");
				operLog.setModule("文章管理");
			} else if (Constants.POSTER_APPROVE.equals(approveType)) {// 审批海报

				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(), thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					JSONObject json = JSONObject.parseObject(dbtsa.getContent());
					TbSpPoster tsp = JSONObject.toJavaObject(json, TbSpPoster.class);
					TbSpPoster dbpost = posterDao.save(tsp);
					// 先清空
					animatedTextDao.deleteByPosterId(tsp.getId());

					List<PosterAnimatedText> animatedTexts = tsp.getAnimatedTexts();
					// posterAnimatedTextDao.save(animatedTexts);
					if (CollectionUtils.isNotEmpty(animatedTexts)) {
						for (PosterAnimatedText text : animatedTexts) {
							text.setPosterId(dbpost.getId());
							animatedTextDao.save(text);
						}
					}
				}
				operLog.setContent("审批ID为" + id + "的海报的添加或者修改--通过");
				operLog.setModule("海报管理");
			}
		} else if ("no".equals(type)) {

			dbtsa.setStatus(Constants.APPROVE_NO);
			approveDao.save(dbtsa);
			// approveDao.updateStatus("2", approveType, id);
			if (Constants.PRODUCT_APPROVE.equals(approveType)) {// 将机构下店铺产品置为无效
				TbSpProduct dbtsp = productDao.findById(id).get();
				if (null == dbtsp.getModifyTime() && null == dbtsp.getModifyUser()) {
					productDao.updateStatus(Constants.FALSE, id);
				} else {
					productDao.updateStatus(dbtsa.getOriginalStatus(), id);
				}
				operLog.setContent(userId + "审批ID为" + id + "的产品的添加或者修改--拒绝");
				operLog.setModule("产品管理");
			}
			if (Constants.ARTICLE_APPROVE.equals(approveType)) {
				/// TbSpArticle db = articleDao.findOne(id);
				TbSpArticle db = articleDao.findById(id).get();
				if (null == db.getModifyTime() && null == db.getModifyUser()) {
					// 新添加的
					articleDao.updateStatus(Constants.FALSE, id);// 状态回写
				} else {
					articleDao.updateStatus(dbtsa.getOriginalStatus(), id);// 状态回写
				}
				operLog.setContent("审批ID为" + id + "的文章的添加或者修改--拒绝");
				operLog.setModule("文章管理");
			}
			if (Constants.POSTER_APPROVE.equals(approveType)) {
				TbSpPoster db = posterDao.findById(id).get();
				if (null == db.getModifyTime() && null == db.getModifyUser()) {
					// 新添加的
					posterDao.updateStatus(Constants.FALSE, id);// 状态回写
				} else {
					posterDao.updateStatus(dbtsa.getOriginalStatus(), id);// 状态回写
				}
				operLog.setContent("审批ID为" + id + "的海报的添加或者修改--拒绝");
				operLog.setModule("海报管理");
			}
		}
		operationLogDao.save(operLog);
		sr.setSuccess();
		return sr;
	}

	@Override
	public ServiceResult approveHistory(String type, Integer id, Integer pageNumber, Integer pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.ASC, "status");
		/// Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
		Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
		sr.setResult(approveDao.findByTypeAndApproveIdList(type, id.toString(), pageable));
		return sr;
	}

	@Override
	public ServiceResult allPoster(String branchCode, String serchKey, String type, Integer pageNumber, Integer pageSize, String userCode) {
		TbSysHotarea hot = hotareaDao.findByAreaCode(branchCode);
		ServiceResult sr = new ServiceResult();
		StringBuilder sql = new StringBuilder();
		List<Map<String, Object>> proList = null;
		Integer sqlPageNumber = (pageNumber - 1) * pageSize;
		sql.append("select p.PRODUCT_ID,p.ID as id,p.NAME as name,p.type as type,p.RISKCODE as riskCode,p.PRODUCT_ID as productId,"
				+ "p.PRODUCT_NAME as productName,p.BIGIMG_URL as bigImgUrl,p.SUMMARY_INFO as summaryInfo,p.img_url as imgUrl,"
				+ "p.STATUS as status,p.COORDINATE_X_Q_R_CODE as coordinateXQRCode,p.COORDINATE_Y_Q_R_CODE as coordinateYQRCode,"
				+ "p.WIDTH_Q_R_CODE as widthQRCode,p.HEIGHT_Q_R_CODE as heightQRCode,\r\n"
				+ "if(p.PRODUCT_ID,(select pro.rate from tb_sp_productconfig pro where  pro.Branch_code=? and pro.STATUS=1 and pro.Product_id = p.PRODUCT_ID) , null) as rate  from t_sp_poster p  ");
		// 条件
		sql.append(" where  p.status in ('1','3') ");
		if (StringUtils.isNotEmpty(type) && "all".equals(type)) {

			if (StringUtils.isNotEmpty(serchKey)) {
				sql.append(" and p.NAME like ? ");
				sql.append(" order by p.Create_date desc,p.ID asc LIMIT " + sqlPageNumber.toString() + "," + pageSize.toString());
				// proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] {
				// branchCode, "%" + serchKey + "%" });
				proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] { hot.getBranchCode(), "%" + serchKey + "%" });
			} else {
				sql.append(" order by p.Create_date desc,p.ID asc LIMIT " + sqlPageNumber.toString() + "," + pageSize.toString());
				// proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] {
				// branchCode });
				proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] { hot.getBranchCode() });
			}
		} else {
			sql.append(" and p.type =? ");
			if (StringUtils.isNotEmpty(serchKey)) {
				sql.append(" and p.NAME like ? ");
				sql.append(" order by p.Create_date desc,p.ID asc LIMIT " + sqlPageNumber.toString() + "," + pageSize.toString());
				// proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] {
				// branchCode, type, "%" + serchKey + "%" });
				proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] { hot.getBranchCode(), type, "%" + serchKey + "%" });
			} else {
				sql.append(" order by p.Create_date desc,p.ID asc LIMIT " + sqlPageNumber.toString() + "," + pageSize.toString());
				// proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] {
				// branchCode, type });
				proList = readJdbcTemplate.queryForList(sql.toString(), new Object[] { hot.getBranchCode(), type });
			}
		}
		Boolean isShowRate = shopService.isSetRate(userCode);
		// List<TbSpPoster> returnList = Lists.newArrayList();
		// for (int i = 0; i < proList.size(); i++) {// 遍历设置实体
		// TbSpPoster post = new TbSpPoster();
		// post.setId((Integer) proList.get(i).get("ID"));
		// post.setName((String) proList.get(i).get("NAME"));
		// post.setType((String) proList.get(i).get("type"));
		// post.setRiskCode((String) proList.get(i).get("RISKCODE"));
		// post.setProductId((Integer) proList.get(i).get("PRODUCT_ID"));
		// post.setProductName((String) proList.get(i).get("PRODUCT_NAME"));
		// post.setStatus((String) proList.get(i).get("STATUS"));
		// post.setBigImgUrl((String) proList.get(i).get("BIGIMG_URL"));
		// post.setImgUrl((String) proList.get(i).get("img_url"));
		// post.setViews((Integer) proList.get(i).get("views"));
		// post.setUserId((String) proList.get(i).get("USER_ID"));
		// post.setCreateDate((Date) proList.get(i).get("Create_date"));
		// post.setModifyUser((String) proList.get(i).get("MODIFY_USER"));
		// post.setModifyTime((Date) proList.get(i).get("MODIFY_TIME"));
		// post.setApproveStatus((String) proList.get(i).get("Approve_Status"));
		// post.setSummaryInfo((String) proList.get(i).get("SUMMARY_INFO"));
		//
		// List<PosterAnimatedText> animatedTexts =
		// animatedTextDao.findByPosterId(post.getId());
		// if (CollectionUtils.isNotEmpty(animatedTexts)) {
		// post.setAnimatedTexts(animatedTexts);
		// }
		//
		// if ("2".equals(post.getType())) {
		// Object rate = proList.get(i).get("rate");
		// Double rates = shopService.getRate(Double.parseDouble(rate.toString()),
		// userCode, proList.get(i).get("productId").toString());
		// post.setRate(rates);
		// }
		// returnList.add(post);
		// }
		// sr.setResult(returnList);
		//
		// return sr;
		RateDto rateDto = insureService.getLevelRate(userCode);
		String userTop = rateDto.getUserCode();
		Double levenRate = rateDto.getRate();
		List<Map<String, Object>> newProList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> map : proList) {
			if ("2".equals(map.get("type").toString())) {
				Object rate = map.get("rate");
				if (isShowRate) {
					map.put("rate",
							shopService.getRate(Double.parseDouble(rate.toString()), userTop, map.get("productId").toString(), false) * levenRate);
				} else {
					map.put("rate", 0.0);
				}
			}
			Integer posterId = Integer.parseInt(map.get("id").toString());
			List<PosterAnimatedText> animatedTexts = animatedTextDao.findByPosterId(posterId);
			map.put("animatedTexts", animatedTexts);
			newProList.add(map);
		}
		sr.setResult(newProList);

		return sr;
	}

	@Override
	public ServiceResult findPoster(Integer id) {
		ServiceResult sr = new ServiceResult();
		TbSpPoster poster = posterDao.findById(id).get();

		List<PosterAnimatedText> animatedTexts = animatedTextDao.findByPosterId(id);
		poster.setAnimatedTexts(animatedTexts);

		// try {
		// String filePath =
		// "C:\\app\\saleplatform\\web\\upload\\assets\\x3\\logo.png";// 文件路径
		// String base64Code = fileUploadService.encodeBase64File(filePath);// 获取base64码
		// String suffix = filePath.substring(filePath.lastIndexOf(".") + 1,
		// filePath.length());// 后缀
		// poster.setSummaryInfo("data:image/" + suffix + ";base64," + base64Code);//
		// 输出图像
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		sr.setResult(poster);
		return sr;
	}

	@Override
	public ServiceResult waitAapprove(String approveType, String status, Integer pageNumber, Integer pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");
		String userId = Current.userId.get();
		Integer roleId = roleUserDao.findByUserid(userId).getRoleid();
		Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
		Page<TbSpApprove> page = approveDao.findByTypeAndStatus(approveType, status, pageable);
		List<TbSpApprove> list = page.getContent();
		for (TbSpApprove tsa : list) {
			TbSpFlowDetail flowDetail = flowDetailDao.findByNoAndNode(tsa.getFlowNo(), tsa.getFlowNode());
			if (null != flowDetail && StringUtils.isNotBlank(flowDetail.getUserCode())) {// 用户审批
				String[] users = flowDetail.getUserCode().split("&");
				boolean b = Arrays.asList(users).contains(userId);
				if (b) {
					tsa.setApproveAuth("true");
				} else {
					tsa.setApproveAuth("false");
				}
			}
			if (null != flowDetail && StringUtils.isNotBlank(flowDetail.getRoleCode())) {// 角色审批
				String[] roles = flowDetail.getRoleCode().split("&");
				boolean b = Arrays.asList(roles).contains(roleId.toString());
				if (b) {
					tsa.setApproveAuth("true");
				} else {
					tsa.setApproveAuth("false");
				}
			}
		}
		sr.setResult(page);
		return sr;
	}

}
